<template>
	<el-container style="height: 100vh">
		<el-aside v-loadING="menuloading" width="300px" style="border-right: 1px solid var(--el-border-color-light)">
			<el-container style="height: 100%">
				<el-header style="padding: 15px; border-bottom: 1px solid var(--el-border-color-light)">
					<el-input v-model="menuFilterText" placeholder="输入关键字进行过滤" clearable />
				</el-header>
				<el-main class="nopadding" style="overflow: hidden">
					<el-tree
						ref="menu"
						class="menu"
						node-key="id"
						:data="menuList"
						:props="menuProps"
						draggable
						highlight-current
						:expand-on-click-node="false"
						check-strictly
						:filter-node-method="menuFilterNode"
						@node-click="menuClick"
						@node-drop="nodeDrop"
						style="height: 100%; overflow: auto"
					>
						<template #default="{ node, data }">
              <span class="custom-tree-node el-tree-node__label">
                <span class="label">
                  {{ node.label }}
                </span>
                <span class="do">
                  <el-icon @click.stop="add(node, data)"><el-icon-plus /></el-icon>
                </span>
              </span>
	</template>
					</el-tree>
				</el-main>
				<el-footer style="height: 51px; display: flex; align-items: center; padding: 0 15px; border-top: 1px solid var(--el-border-color-light)">
					<el-button type="primary" size="small" icon="el-icon-plus" @click="add()"></el-button>
					<el-button type="danger" size="small" plain icon="el-icon-delete" @click="delMenu"></el-button>
				</el-footer>
			</el-container>
		</el-aside>
		<el-container>

			<el-main ref="main" class="nopadding" style="padding: 20px; overflow: hidden">
				<div
					style="height: 100%; box-shadow: var(--el-border-color-light) 0px 0px 10px"
					class="container"
				>
					<el-splitter
						layout="vertical"
						style="height: 100%"
						:model-value="splitterRatio"
						@update:model-value="handleSplitterChange"
					>
						<el-splitter-panel
							:size="splitterRatio[0]"
							:min-size="10"
							style="
							overflow: hidden;
							display: flex;
							flex-direction: column;
							height: 100%; /* 确保 splitter panel 高度100% */
  "
						>
							<el-tabs
								v-model="sqlEditorTabsValue"
								type="card"
								closable
								class="demo-tabs"
								@tab-remove="removeTab"
								style="
								  height: 100%;
								  display: flex;
								  flex-direction: column;
    "
							>
								<el-tab-pane
									v-for="item in sqlEditableTabs"
									:key="item.name"
									:label="item.title"
									:name="item.name"
									style="
									height: 100%;
									display: flex;
									flex-direction: column;
      "
								>
									<el-header style="flex: 0 0 auto;"> <!-- header 不伸缩 -->
										<div class="left-panel">
											<el-button icon="el-icon-videoPlay" circle @click="addTab(editableTabsValue)"></el-button>
											<el-button icon="el-icon-Stopwatch" circle />
											<el-button icon="el-icon-CircleCheckFilled" circle />
											<el-button icon="el-icon-Management" circle />
											<el-button type="danger" icon="el-icon-Delete" circle />
										</div>
									</el-header>
									<sc-code-editor
										ref="editor"
										v-model="sql"
										mode="sql"
										:sqlTables="databaseSchema"
										style="
          flex: 1; /* 填充剩余空间 */
          min-height: 0; /* 防止 flex item 溢出 */
          height: 100%;
          overflow: auto;
        "
									></sc-code-editor>
								</el-tab-pane>
							</el-tabs>
						</el-splitter-panel>

						<!— 下方面板  !important; background: var(--el-color-success-light-9) -->
						<el-splitter-panel
							:size="splitterRatio[1]"
							:min-size="10"
							style="overflow: hidden "
						>
							<el-tabs
								v-model="editableTabsValue"
								type="card"
								closable
								class="demo-tabs"
								@tab-remove="removeTab"
							>
								<el-tab-pane
									v-for="item in editableTabs"
									:key="item.name"
									:label="item.title"
									:name="item.name"
								>
										<component :is="item.component" />
								</el-tab-pane>
							</el-tabs>
						</el-splitter-panel>
					</el-splitter>
				</div>
			</el-main>

		</el-container>
	</el-container>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted ,onBeforeUnmount, defineAsyncComponent } from 'vue'
import json from '../../mock/menu2.json';
import t1 from './t1.vue'
const scCodeEditor = defineAsyncComponent(() => import('@/components/scCodeEditor'))
const 	sql = `SELECT \`author\`, \`title\` FROM \`posts\`
WHERE \`status\` = 'draft' AND \`author\` IN('author1','author2')
ORDER BY \`created_at\` DESC, \`id\` DESC LIMIT 0, 10;`
const editableTabsValue = ref('1')
const sqlEditorTabsValue = ref('1')

const sqlEditableTabs = ref([
	{
		title: 'SQL编辑器',
		name: '1',
		content: 'SQL编辑器内容',
	},
])
const editableTabs = ref([
	{
		title: '控制台',
		name: '1',
		content: '控制台内容',
	},
])
let tabIndex = 1
const newMenuIndex = ref(1);
const menuloading = ref(false);
const menuList = ref([]);
const menuFilterText = ref('');
const menuRef = ref(null);
const mainRef = ref(null);
const editor = ref(null)
// 树形菜单配置
const menuProps = {
	label: (data) => data.meta.title
};
// 分割比例 [上, 下]
const splitterRatio = ref([50, 50]);
// 分割条拖动回调
const handleSplitterChange = (ratio) => {
	splitterRatio.value = ratio;
	console.log('当前分割比例:', ratio);
};
// 方法定义
const getMenu = () => {
	menuloading.value = true;
	const res = json;
	menuloading.value = false;
	menuList.value = res.data.menu;
};

const menuClick = (data, node) => {
	const pid = node.level === 1 ? undefined : node.parent.data.id;
};

const menuFilterNode = (value, data) => {
	if (!value) return true;
	const targetText = data.meta.title;
	return targetText.includes(value);
};

const nodeDrop = (draggingNode, dropNode, dropType) => {
	console.log(`拖拽对象：${draggingNode.data.meta.title}, 释放对象：${dropNode.data.meta.title}, 释放对象的位置：${dropType}`);
};

const add = async (node, data) => {
	const newMenuName = `未命名${newMenuIndex.value++}`;
	const newMenuData = {
		parentId: data ? data.id : '',
		name: newMenuName,
		path: '',
		component: '',
		meta: {
			title: newMenuName,
			type: 'menu'
		}
	};

	menuloading.value = true;
	// 实际项目中替换为真实的API调用
	// const res = await $API.demo.post.post(newMenuData);
	const res = { data: Date.now() }; // 模拟响应
	menuloading.value = false;

	newMenuData.id = res.data;
	menuRef.value.append(newMenuData, node);
	menuRef.value.setCurrentKey(newMenuData.id);
};

const delMenu = async () => {
	const CheckedNodes = menuRef.value.getCheckedNodes();
	if (CheckedNodes.length === 0) {
		console.warn('请选择需要删除的项');
		return;
	}

	// 实际项目中应该使用ElMessageBox.confirm
	const confirm = window.confirm('确认删除已选择的菜单吗？');
	if (!confirm) return;

	menuloading.value = true;
	// const reqData = { ids: CheckedNodes.map(item => item.id) };
	// const res = await $API.demo.post.post(reqData);
	const res = { code: 200 }; // 模拟响应
	menuloading.value = false;

	if (res.code === 200) {
		CheckedNodes.forEach((item) => {
			const node = menuRef.value.getNode(item);
			menuRef.value.remove(item);
		});
	} else {
		console.warn(res.message || '删除失败');
	}
};

const handleResize = () => {
	console.log('Window resized');
};


const addTab = (targetName: string) => {
	const newTabName = `${++tabIndex}`
	editableTabs.value.push({
		title: '运行结果' + (tabIndex -1),
		name: newTabName,
		component: t1,
	})
	editableTabsValue.value = newTabName
}
const removeTab = (targetName: TabPaneName) => {
	const tabs = editableTabs.value
	let activeName = editableTabsValue.value
	if (activeName === targetName) {
		tabs.forEach((tab, index) => {
			if (tab.name === targetName) {
				const nextTab = tabs[index + 1] || tabs[index - 1]
				if (nextTab) {
					activeName = nextTab.name
				}
			}
		})
	}

	editableTabsValue.value = activeName
	editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
}


// 生命周期
onMounted(() => {
	getMenu();
	window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
	window.removeEventListener('resize', handleResize);
});

// 监听器
watch(menuFilterText, (val) => {
	menuRef.value.filter(val);
});
</script>


<style scoped>

.nopadding {
	padding: 0 !important;
}
.custom-tree-node {
	display: flex;
	flex: 1;
	align-items: center;
	justify-content: space-between;
	font-size: 14px;
	padding-right: 24px;
	height: 100%;
}
.custom-tree-node .label {
	display: flex;
	align-items: center;
	height: 100%;
}
.custom-tree-node .label .el-tag {
	margin-left: 5px;
}
.custom-tree-node .do {
	display: none;
}
.custom-tree-node .do i {
	margin-left: 5px;
	color: #999;
}
.custom-tree-node .do i:hover {
	color: #333;
}

.custom-tree-node:hover .do {
	display: inline-block;
}

</style>
